﻿using System;
using System.Collections.Generic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Linq.Extensions;
using Hicap.AuthorizationServer.Application.Dto;
using Hicap.AuthorizationServer.Application.Dto.Common;
using Hicap.AuthorizationServer.Core.Managers;
using Hicap.AuthorizationServer.Core.Models;
using Microsoft.EntityFrameworkCore;

namespace Hicap.AuthorizationServer.Application.Sys
{
    public class RoleAppService : AuthorizationServerApplicationBase<Role, RoleListDto, RoleEditDto>
    {
        private readonly IRoleManager _manager;
        private readonly IAuthObjectRoleRelatedManager _authObjectRoleRelatedManager;
        private readonly IAuthObjectManager _authObjectManager;

        public RoleAppService(IRoleManager manager,
            IAuthObjectRoleRelatedManager authObjectRoleRelatedManager,
            IAuthObjectManager authObjectManage) : base(manager)
        {
            _manager = manager;
            _authObjectRoleRelatedManager = authObjectRoleRelatedManager;
            _authObjectManager = authObjectManage;
        }

        /// <summary>
        /// 获取User的分页列表信息
        /// </summary>
        /// <param name="queryInput"></param>
        /// <returns></returns>
        public override async Task<PagedResultDto<RoleListDto>> PagedDatas(QueryInput queryInput)
        {
            System.Linq.IQueryable<Role> query = GetQuery(_manager.GetQuery(null), queryInput);

            int roleCount = await query.CountAsync();

            List<Role> roles;

            roles = await query
               .OrderBy(queryInput.Sorting)
               .PageBy(queryInput)
               .ToListAsync();

            List<RoleListDto> roleListDtos = roles.MapTo<List<RoleListDto>>();
            foreach (RoleListDto roleListDto in roleListDtos)
            {
                List<Expression<Func<AuthObjectRoleRelated, dynamic>>> keys = new List<Expression<Func<AuthObjectRoleRelated, dynamic>>>()
          {
              x => x.AuthObject,
              x => x.Role
          };

                foreach (AuthObjectRoleRelated authObjectRoleRelated in _authObjectRoleRelatedManager
                    .GetQuery(y => y.Role.Id == roleListDto.Id))
                {
                    //AuthObject auth = _authObjectRoleRelatedManager.GetQuery
                    //    (z => z.AuthObjectId == authObjectRoleRelated.AuthObjectId);
                    AuthObject auth = _authObjectManager.GetAuthById(authObjectRoleRelated.AuthObjectId);
                    AuthObjectListDto map = auth.MapTo<AuthObjectListDto>();
                    map.AuthRoleReleatedId = authObjectRoleRelated.Id;
                    roleListDto.AuthObject.Add(map);
                }
            }

            return new PagedResultDto<RoleListDto>(
                roleCount,
                roleListDtos
            );
        }
    }
}